<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Row :gutter="16">
        <Col span="4">
          <Input
            v-model="params.keyword"
            type="text"
            placeholder="请输入姓名/电话"
            @on-enter="entryKeyword"
            :clearable="true"
            @on-clear="entryKeyword"
          ></Input>
        </Col>
        <Col span="4">
          <Select
            v-model="params.project_id"
            placeholder="请选择项目"
            clearable
            @on-change="changeProject"
          >
            <Option
              v-for="(item, index) in projectList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </Col>
        <Col span="16" class="ivu-text-right">
          <Button
            v-hasC="{
              name: 'rbac-personnel-create',
              flag: 'v1/rbac/personnel/create',
            }"
            type="primary"
            @click="handleCreate('add')"
            >新增</Button
          >
          <!-- <Button
            v-hasC="{
              name: 'rbac-personnel-sync',
              flag: 'v1/rbac/personnel/sync',
            }"
            type="success"
            @click="handleUpdate"
            class="ivu-ml-8"
            >同步钉钉</Button
          > -->
        </Col>
      </Row>
      <Table
        highlight-row
        :columns="columns"
        :data="data"
        class="ivu-mt-16"
        :loading="loading"
      >
        <template slot-scope="{ row }" slot="realname">
          <Icon type="md-person" v-if="row.is_project_admin == 1" />
          {{ row.realname }}
        </template>
        <template slot-scope="{ row }" slot="status">
          <Badge
            v-if="+row.status === 1"
            status="success"
            :text="row.status_str"
          ></Badge>
          <Badge
            v-if="+row.status === 0"
            status="error"
            :text="row.status_str"
          ></Badge>
        </template>
        <template slot="center" slot-scope="{ row }">
          <div>{{ row.config_name_arr.join(",") }}</div>
        </template>
        <template slot-scope="{ row }" slot="project">
          <div>
            {{ row.project_name_arr.join(",") }}
          </div>
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a
            v-hasC="{
              name: 'rbac-personnel-update',
              flag: 'v1/rbac/personnel/update',
            }"
            @click="handleCreate('edit', row)"
            >编辑</a
          >
        </template>
      </Table>
      <div class="ivu-mt iuv-text-center" style="text-align: center;">
        <Page
          :total="total"
          show-total
          show-elevator
          show-sizer
          @on-change="changePage"
          :page-size="params.pageSize"
          @on-page-size-change="changePageSize"
        ></Page>
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="person ? '新增' : '编辑'"
      width="800"
      @on-cancel="cancel"
      :draggable="true"
    >
      <Form ref="form" :model="form" :label-width="80" :rules="ruleInline">
        <Row :gutter="12">
          <Col span="12">
            <FormItem label="姓名" prop="name">
              <Input v-model="form.name" placeholder="请输入姓名"></Input>
            </FormItem>
            <FormItem label="帐号">
              <Input
                style="color: black;"
                disabled="disabled"
                v-model="form.phone"
              ></Input>
            </FormItem>
            <!-- <FormItem label="营销中心">
              <Select
                v-model="form.net_config_id"
                multiple
                clearable
                :max-tag-count="3"
                placeholder="请选择营销中心"
              >
                <Option
                  v-for="item in centerLists"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem> -->
            <FormItem label="项目" prop="project">
              <Select
                v-model="form.project"
                multiple
                clearable
                :max-tag-count="3"
                placeholder="请选择项目"
                @on-change="changePro"
                :transfer="false"
              >
                <Option
                  v-for="item in projectLists"
                  :key="item.value"
                  :value="item.value"
                  :disabled="item.disabled == 1"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
            <FormItem label="管理员">
              <i-switch v-model="form.is_project_admin">
                <span slot="open">On</span>
                <span slot="close">Off</span>
              </i-switch>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="手机号" prop="phone">
              <Input v-model="form.phone" placeholder="请输入手机号"></Input>
            </FormItem>
            <FormItem label="密码" prop="password">
              <Input v-model="form.password" placeholder="请输入"></Input>
            </FormItem>
            <FormItem label="状态">
              <i-switch v-model="form.switch">
                <span slot="open">On</span>
                <span slot="close">Off</span>
              </i-switch>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button type="primary" :loading="remarksloading" @click="submit"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getPersonalList,
  addPersonal,
  editPersonal,
  syncPersonal,
  selectInfo,
} from "@/api/TApi/index.js";

export default {
  name: "diagnosis",
  data() {
    const validatePhone = (rule, value, callback) => {
      var reg = /^[1][0-9]{10}$/;
      if (!reg.test(value)) {
        callback(new Error("请填写正确的手机号"));
      } else {
        callback();
      }
    };
    const validateProject = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请选择项目"));
      } else {
        callback();
      }
    };
    return {
      modal: false,
      person: true,
      loading: false,
      remarksloading: false,
      total: 0,
      projectList: [],
      projectLists: [],
      centerLists: [],
      // 获取列表参数
      params: {
        page: 1,
        pageSize: 10,
        keyword: "",
        project_id: "",
      },
      //   新增编辑表单
      form: {
        name: "",
        phone: "",
        project: [],
        accounts: "",
        password: "",
        switch: true,
        center: "",
        is_project_admin: false,
        // net_config_id: [],
      },
      project: [],
      projects_num: [],
      // 表单验证逻辑
      ruleInline: {
        name: {
          required: true,
          message: "请填写姓名",
          trigger: "blur",
        },
        phone: {
          validator: validatePhone,
          required: true,
          trigger: "blur",
        },
        project: {
          validator: validateProject,
          required: true,
          trigger: "change",
        },
        password: {
          message: "请填写密码",
          trigger: "blur",
        },
      },
      editId: "",
      columns: [
        {
          title: "名称",
          slot: "realname",
          width: 100,
        },
        {
          title: "手机号",
          key: "mobile",
          width: 140,
        },
        {
          title: "用户唯一标识",
          key: "mobile_encrypt",
        },
        {
          title: "项目",
          slot: "project",
          minWith: 220,
        },
        {
          title: "最后登录时间",
          key: "last_time",
          width: 150,
        },
        {
          title: "状态",
          slot: "status",
          width: 80,
        },
        {
          title: "操作",
          slot: "operation",
          width: 80,
        },
      ],
      data: [],
      member_id: 0,
      projects: [],
    };
  },
  created() {
    // 执行初始化数据
    this.params.project_id = this.$route.query.id;
    this._getPersonalList();
  },
  methods: {
    changePro(e) {
      if (this.projects.length > e.length) {
        this.$Modal.confirm({
          title: "提示",
          content: `删除项目前，请将该项目下员工数据重新分配，然后再去除项目。否则该员工数据将会全部释放进公海。`,
          onOk: () => {
            this.projects = this.form.project;
          },
          onCancel: () => {
            this.form.project = this.projects;
          },
        });
      } else {
        this.projects = this.form.project;
      }
    },
    // 点击取消
    cancel() {
      this.modal = false;
      this.projects = [];
      this.form.project = [];
      // this.form.net_config_id = [];
    },
    changePageSize(value) {
      this.params.pageSize = value;
      this._getPersonalList();
    },
    //   点击确定
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.remarksloading = true;
          setTimeout(() => {
            this.remarksloading = false;
          }, 1000);
          let params = {
            name: this.form.name,
            mobile: this.form.phone,
            project_ids: this.form.project.join(","),
            // net_config_id: this.form.net_config_id.join(","),
            password: this.form.password,
            re_password: this.form.password,
            status: this.form.switch ? 1 : 0,
            is_project_admin: this.form.is_project_admin ? 1 : 0,
            id: this.editId,
          };
          if (this.person) {
            delete params.id;
            addPersonal(params).then((res) => {
              this.modal = false;
              // this.form.net_config_id = [];
              this._getPersonalList();
              this.$Message.success("新增员工成功");
            });
          } else {
            let obj = {};
            for (let num of this.form.project) {
              obj[`${num}`] = "a";
            }
            let projects_arr = [];
            for (let i of this.project) {
              if (obj[i]) {
                projects_arr.push(i);
              }
            }
            if (projects_arr.length > 0 && !this.form.switch) {
              let html = "";
              for (let items of projects_arr) {
                for (let item of this.projects_num) {
                  if (+items === +item.project_id && +item.num > 0) {
                    html += `项目：${item.name}有<font color='red'>${item.num}</font>个患者，`;
                  }
                }
              }
              if (html) {
                this.$Modal.confirm({
                  title: "提示",
                  content: `<p>当前员工下${html}请分配给其它员工，否则患者数据会切到公海（回访部切到鱼池）。</p>`,
                  onOk: () => {
                    editPersonal(params).then((res) => {
                      this.modal = false;
                      // this.form.net_config_id = [];
                      this._getPersonalList();
                      this.$Message.success("编辑员工成功");
                    });
                  },
                  onCancel: () => {},
                });
              } else {
                editPersonal(params).then((res) => {
                  this.modal = false;
                  this._getPersonalList();
                  this.$Message.success("编辑员工成功");
                });
              }
            } else {
              editPersonal(params).then((res) => {
                this.modal = false;
                this._getPersonalList();
                this.$Message.success("编辑员工成功");
              });
            }
          }
        }
      });
    },
    // 获取营销中心和项目下拉接口v2.06
    _getselectInfo() {
      selectInfo({ member_id: this.member_id }).then((res) => {
        this.centerLists = res.config;
        this.projectLists = res.project;
      });
    },
    // 获取列表
    _getPersonalList() {
      this.loading = true;
      let params = JSON.parse(JSON.stringify(this.params));
      getPersonalList(params).then((res) => {
        this.projectList = res.condition.project;
        this.total = res.total;
        this.data = res.list;
        this.loading = false;
      });
    },
    // 切换分页
    changePage(value) {
      this.params.page = value;
      this._getPersonalList();
    },
    // 切换项目
    changeProject(value) {
      this.params.page = 1;
      this._getPersonalList();
    },
    // 输入关键字回车
    entryKeyword() {
      this.params.page = 1;
      this.params.project_id = "";
      this._getPersonalList();
    },
    handleCreate(type, data) {
      console.log(this.projects);
      this.projects = [];
      this.$refs.form.resetFields();
      this.modal = true;
      switch (type) {
        case "add":
          {
            this.person = true;
            this.member_id = 0;
            selectInfo({ member_id: this.member_id }).then((res) => {
              this.centerLists = res.config;
              this.projectLists = res.project;
              this.form.switch = true;
              this.form.is_project_admin = false;
            });
          }
          break;
        case "edit":
          {
            this.editId = data.id;
            this.person = false;
            this.member_id = data.id;
            selectInfo({ member_id: this.member_id }).then((res) => {
              this.centerLists = res.config;
              this.projectLists = res.project;
              this.form.name = data.realname;
              this.form.phone = data.mobile;
              this.form.project = data.project_id_arr;
              this.projects = data.project_id_arr;
              // this.form.net_config_id = data.config_id_arr;
              this.project = JSON.parse(JSON.stringify(data.project_id_arr));
              this.projects_num = JSON.parse(
                JSON.stringify(data.patient_num_arr)
              );
              for (let item of this.projects_num) {
                for (let items of this.projectLists) {
                  if (+items.id === +item.project_id) {
                    items["num"] = item.num;
                  }
                }
              }
              this.form.is_project_admin = +data.is_project_admin === 1;
              this.form.switch = +data.status === 1;
            });
          }
          break;
      }
    },

    handleDrawerCancel() {
      this.$Message.warning("已取消!");
    },
    handleSubmit() {
      this.$Message.success("操作成功!");
    },
    handleUpdate() {
      this.$Modal.confirm({
        title: "钉钉同步",
        content: "请确定是否同步数据",
        loading: true,
        onOk: () => {
          syncPersonal().then((res) => {
            this.$Modal.remove();
          });
        },
      });
    },
  },
};
</script>

<style scoped></style>
